<?php

namespace Lib;

class Router {

    private static $matches;
    private static $instance;
    
    public static function getInstance($ini_file = 'Config/route.ini'){
        if(!self::$instance){
            self::$instance = new Router($ini_file);
        }
        return self::$instance;
    }
    
    private function __construct($ini_file) {
       if(!self::$matches){
            self::$matches = parse_ini_file(SITE_PATH . $ini_file, TRUE);
       }
    }
    
    public function setPath($path) {
        $path = trim($path, '/\\');
        $path = SITE_PATH . $path . DIRSEP;
        if (is_dir($path) == false) {
            throw new \Exception('Invalid controller path: `' . $path . '`');
        }
        $this->path = $path;
    }

    function delegate($path = '') {

        $this->getController($path);

        $class = '\\Module\\' . Registry::get('controller') . 'Module';
        $action = Registry::get('action') . 'Action';

        if(!class_exists($class)){
            return \Lib\Registry::get('view')->renderModule('/utils/pageNotFound');
        }
        
        $controller = new $class();
        
        if (!is_callable(array($controller, $action))) {
            return \Lib\Registry::get('view')->renderModule('/utils/pageNotFound');
        }

        $controller->$action();
    }

    private function getController($path) {

        if(empty($path)){
            $path = $_SERVER['REQUEST_URI'];
        }
        
        $parseResult = $this->check($path);
        Registry::set('controller', $parseResult['Module']);
        Registry::set('action', $parseResult['Action']);
        Registry::set('args', $parseResult['params']);
    }
    
    private function check($match) {

        foreach (self::$matches as $m) {
            if (preg_match($m['pattern'], $match, $matches)) {
                $params = explode('|', $m['params']);
                $m['params'] = array();
                if (count($params) > 0) {
                    foreach ($params as $v) {
                        if (!empty($v)) {
                            list($key, $value) = explode('=', $v);
                            $m['params'][$key] = $matches[$value];
                        }
                    }
                }
                return $m;
            }
        }
    }

}

?>
